import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { verifyToken } from '@/app/lib/auth';
import prisma from '@/app/lib/prisma';

export async function POST(request: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    const { date, mealType, foods } = await request.json();

    // 计算总营养值
    const totalNutrition = foods.reduce(
      (acc: any, food: any) => ({
        calories: acc.calories + food.calories,
        protein: acc.protein + food.protein,
        carbs: acc.carbs + food.carbs,
        fat: acc.fat + food.fat,
      }),
      { calories: 0, protein: 0, carbs: 0, fat: 0 }
    );

    const record = await prisma.dietRecord.create({
      data: {
        userId: payload.userId,
        date: new Date(date),
        mealType,
        foods: JSON.stringify(foods),
        ...totalNutrition,
      },
    });

    return NextResponse.json({ record });
  } catch (error) {
    console.error('添加饮食记录错误:', error);
    return NextResponse.json(
      { message: '添加饮食记录失败' },
      { status: 500 }
    );
  }
}

export async function GET(request: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    const records = await prisma.dietRecord.findMany({
      where: { userId: payload.userId },
      orderBy: { date: 'desc' },
      take: 10,
    });

    const formattedRecords = records.map(record => ({
      ...record,
      foods: JSON.parse(record.foods),
    }));

    return NextResponse.json({ records: formattedRecords });
  } catch (error) {
    console.error('获取饮食记录错误:', error);
    return NextResponse.json(
      { message: '获取饮食记录失败' },
      { status: 500 }
    );
  }
} 